package cn.zysheep.codec;

import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;
import org.junit.jupiter.api.Test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @version v1.0
 * @Author: lyw
 * @Date: 2021/8/9
 */
public class Base64Utils {

    /**
     * Base64 编解码。
     */
    @Test
    public void encodeBase64() throws IOException {
        //Base64 编码
        String encodeBase64 = Base64.encodeBase64String("千里之行始于足下".getBytes(StandardCharsets.UTF_8));
        //5Y2D6YeM5LmL6KGM5aeL5LqO6Laz5LiL
        System.out.println(encodeBase64);
        //Base64 解码
        byte[] decodeBase64 = Base64.decodeBase64(encodeBase64);
        String result = new String(decodeBase64);
        //千里之行始于足下
        System.out.println(result);

        FileInputStream fileInputStream = new FileInputStream(new File("D:\\微信图片_20210811143052.jpg"));
        String string = Base64.encodeBase64URLSafeString(fileInputStream.readAllBytes());
        System.out.println(string);


        byte[] bytes = Base64.decodeBase64(string);
        FileOutputStream outputStream = new FileOutputStream(new File("D:\\1.jpg"));
        outputStream.write(bytes);
        outputStream.flush();
    }

    /**
     * 16 进制转换
     *
     * @throws DecoderException
     */
    @Test
    public void test2() throws DecoderException {
        String content = "千里之行始于足下";
        //文本转成 16 进制的字符串
        String hexString = Hex.encodeHexString(content.getBytes());
        //e58d83e9878ce4b98be8a18ce5a78be4ba8ee8b6b3e4b88b
        System.out.println(hexString);

        //将 16 进制的文本转为 10 进制的字节数组，接着即可转为源字符串.
        byte[] decodeHex = Hex.decodeHex(hexString);
        String s = new String(decodeHex);
        //千里之行始于足下
        System.out.println(s);
    }
}
